import api from "../../../common/api";
import locationBehavior from "../../../behaviors/location";
import util from "../../../utils/util";
import { gioBaseLog,gioSetPositionLog } from "../../../common/gioHandler";
import { throttle } from "../../../utils/utilsNew";
Component({
  behaviors: [locationBehavior],
  /**
   * 组件的属性列表
   */
  properties: {
    type: {
      type: String,
      value: ''
    },
    imgArray: {
      type: Array,
      value: ''
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    isShowPositionTitle:false, //是否开启了定位
    address:'',//位置信息
    imgArray: [], //图片数组
    imgMin: 1, //最小图片数
    imgMax: 2, //最大图片数
    lng: '', //经度
    lat:'', //维度
  },

  /**
   * 组件的生命周期
   */
  lifetimes: {
    attached: function () {
      this.comfirm = throttle(this.comfirm.bind(this), 1000)

      this.getWxLocationBe().then((res) => {
        this.setData({
          lng: res.longitude,
          lat: res.latitude
        })
        this.getLocationAuthWindow()
      })
      .catch((err) => {
        console.log(err)
      })
    },
    detached: function () {
      // 在组件实例被从页面节点树移除时执行
    },
  },

  /**
   * 组件的方法列表
   */
  methods: {
    move() {},
    handleHide() {
      this.triggerEvent('close', this.data.imgArray)
    },
    comfirm() {
      this.triggerEvent('comfirm', this.data.imgArray)
    },



    // 开启定位
    openPosition() {
      gioBaseLog('positionAgree')//开启定位埋点
      this.getWxLocationBe()
        .then((res) => {})
        .catch(() => {
          wx.getSetting({
            success: (res) => {
              if (!res.authSetting["scope.userLocation"]) {
                this.openConfirm();
              }
            },
          });
        })
    },
    openConfirm() {
      let that = this
      wx.showModal({
        content: "检测到您没打开定位权限，是否去设置打开？",
        confirmText: "确认",
        cancelText: "取消",
        success: function (res) {
          if (res.confirm) {
            gioSetPositionLog('setPosition','点击确定')
            wx.openSetting({
              success: (res) => {
                if (res.authSetting['scope.userLocation']) {
                  that.getWxLocationWithErrorHandler()
                  .then((res) => {
                    that.setData({
                      lng: res.longitude,
                      lat: res.latitude
                    })
                    that.getLocationAuthWindow()
                  })
                }
              }
            });
          } else if(res.cancel){
            gioSetPositionLog('setPosition','点击取消')
          }
        },
      });
    },


    //根据经纬度获取位置信息
    getLocationAuthWindow() {
      let{lng,lat} = this.data
      return new Promise((resolve, reject) => {
        api.getLocationAuthWindow({lng,lat}, (res) => {
          if(res&&res.data&&res.data.isSuccess){
            let content = res.data.content
            if(content.city==content.province){
              content.address=content.city+content.district+content.address_reference_town_title+content.address_reference_street_title
            } else {
              content.address=content.province+content.city+content.district+content.address_reference_town_title+content.address_reference_street_title
            }
            this.setData({
              isShowPositionTitle:true,
              address: content.address
            })
          }
          resolve()
        })
      })
    },



    // -------------上传图片------------------//
    updownd(e) {
      gioBaseLog('uploPict')//上传名片事件
      let num = this.data.imgMax - this.data.imgArray.length;
      wx.chooseImage({
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        count: num,
        success: (res) => {
          let filePathArr = res.tempFilePaths;
          let promiseList = filePathArr.map((item) => {
            return new Promise((resolve, reject) => {
              util.uploadFiles(item, (res) => {
                try {
                  var id = JSON.parse(res.data)[0].id;
                  var obj = {
                    fileId: id,
                    url: item,
                  };
                  resolve(obj);
                  
                } catch (error) {
                  reject()
                }
              });
            });
          });
          Promise.all(promiseList).then((list) => {
            this.setData({
              imgArray: this.data.imgArray.concat(list)
            });
          });
        },
      });
    },
    handleCancel(e) {
      let id = e.currentTarget.dataset.fileid;
      this.setData({
        imgArray: this.data.imgArray.filter((v) => v.fileId != id),
      });
    }
  }
})